<template lang="pug">
  div
    app-header(fixed,title="查询",v-if="!$helper.isWechat")
    div.content-pad(:style="{top: $helper.isWechat ? '0' : '0.84rem'}")
      app-search-toolbar
      .main-wrapper(ref="mainWrapper")
        .no-data(v-if="lists.length < 1") 暂无查询结果
        ul.wrapper-content(v-else)
          li(v-for="(item,index) in lists")
            app-product(:model="item",@plus="buyProductHandler")
    app-buy-option(:model="currentProduct",:activityId="parseInt(0)",@close="buyOptionCloseHandler")
</template>

<script>
import { Button, Toast } from 'mint-ui'
import BScroll from 'better-scroll'
import Header from 'components/Header'
import Product from 'components/Product'
import BuyOption from 'components/BuyOption'
import SerachToolbar from 'components/SerachToolbar'
export default {
  components: {
    'mt-button': Button,
    'app-header': Header,
    'app-product': Product,
    'app-search-toolbar': SerachToolbar,
    'app-buy-option': BuyOption
  },
  beforeRouteEnter (to, from, next) {
    if (!from.name) {
      next({name: 'home:index'})
    } else {
      next()
    }
  },
  data () {
    return {
      mainScroll: null,
      scrolling: false,
      currentProduct: null,
      keyword: '',
      lists: []
    }
  },
  watch: {
    '$route.params.key': {
      async handler (val, oldval) {
        let toast = Toast('正在加载..')
        const result = await this.$rpc.invoke('product_search', [val]).complete()
        if (result.code) {
          return Toast(result.message)
        }
        this.lists = result.data
        this._initScroll()
        toast.close()
      },
      immediate: true,
      deep: false
    }
  },
  created () {
    this.keyword = this.$route.params.key
  },
  methods: {
    // 初始化滚动条
    _initScroll () {
      if (!this.mainScroll) {
        this.$nextTick(() => {
          this.mainScroll = new BScroll(this.$refs.mainWrapper, {
            probeType: 1,
            click: true,
            scrollbar: {
              fade: true,
              interactive: false
            }
          })
          this.mainScroll.on('scrollStart', () => {
            this.scrolling = true
          })
          this.mainScroll.on('scrollEnd', () => {
            this.scrolling = false
          })
        })
      } else {
        this.$nextTick(() => {
          this.mainScroll.refresh()
        })
      }
    },
    buyProductHandler (model) {
      this.currentProduct = model
    },
    buyOptionCloseHandler () {
      this.currentProduct = null
    }
  }
}
</script>
<style lang="stylus" scoped>
  .content-pad
    position: absolute
    bottom: 1.2rem
    right: 0
    left: 0
    padding: 0
  .main-wrapper
    position: absolute
    bottom: 0
    top: 0
    left: 0
    right: 0
    margin-top: .9rem
    height: 100%
    overflow: hidden
  /*查询工具条*/
  .search-toolbar
    width: 100%
  .no-data
    color: #333
    text-align: center
    padding-top: 3rem
    font-size: .4rem
    height: 100%
</style>
